package com.zhijian.wharf.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.zhijian.autoconfigure.cache.CacheClient;
import com.zhijian.wharf.aop.MiniProgramLoginInterceptor;
import com.zhijian.wharf.aop.WebLoginInterceptor;
import com.zhijian.wharf.service.TokenService;
import com.zhijian.wharf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.BufferedImageHttpMessageConverter;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.DeferredResultMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * web应用拦截，域名、防止xxl注入、定义json解析器
 *
 * @Author chengqing
 * @DateTime 2019年4月14日 下午3:19:04
 * @Version 1.0.1
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    @Autowired
    private CacheClient cacheClient;

    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;

    @Bean
    public WebMvcConfigurer webMvcConfigurer() {
        return new WebMvcConfigurer() {

            //自定义json处理器
            @Override
            public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
                converters.add(fastJsonHttpMessageConverter());
                converters.add(new StringHttpMessageConverter());
                converters.add(new ByteArrayHttpMessageConverter());
                converters.add(new BufferedImageHttpMessageConverter());
            }

            //自定义异常返回处理器
            @Override
            public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
                resolvers.add(responseJsonExceptionHandler());
            }

            @Override
            public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
            }

            //自定义拦截器
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                //web
                registry.addInterceptor(new WebLoginInterceptor(cacheClient, userService, tokenService)).addPathPatterns("/**")
                        .excludePathPatterns(Constants.WEB_TOKEN_EXCLUDE_PATHS);
            }

        };
    }

    @Bean
    public ResponseJsonHandler responseJsonProcessor() {
        return new ResponseJsonHandler(fastJsonHttpMessageConverter());
    }

    /**
     * 自定义Json解析工具:fastjson
     *
     * @return
     */
    @SuppressWarnings("deprecation")
    public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        supportedMediaTypes.add(MediaType.TEXT_HTML);
        fastJsonHttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes);
        fastJsonHttpMessageConverter.setFeatures(SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteMapNullValue, SerializerFeature.QuoteFieldNames,
                SerializerFeature.DisableCircularReferenceDetect);
        return fastJsonHttpMessageConverter;
    }

    /**
     * 自定义处理器前置
     */
    @PostConstruct
    public void init() {
        final List<HandlerMethodReturnValueHandler> originalHandlers = new ArrayList<>(
                requestMappingHandlerAdapter.getReturnValueHandlers());
        final int deferredPos = obtainValueHandlerPosition(originalHandlers, DeferredResultMethodReturnValueHandler.class);
        originalHandlers.add(deferredPos + 1, responseJsonProcessor());
        requestMappingHandlerAdapter.setReturnValueHandlers(originalHandlers);
    }

    private int obtainValueHandlerPosition(final List<HandlerMethodReturnValueHandler> originalHandlers,
                                           Class<?> handlerClass) {
        for (int i = 0; i < originalHandlers.size(); i++) {
            final HandlerMethodReturnValueHandler valueHandler = originalHandlers.get(i);
            if (handlerClass.isAssignableFrom(valueHandler.getClass())) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Bean
    public ResponseJsonExceptionHandler responseJsonExceptionHandler() {
        return new ResponseJsonExceptionHandler(fastJsonHttpMessageConverter());
    }


}
